from flask import Flask, render_template, request, jsonify, session, redirect, url_for
import json
import os
from datetime import datetime, timedelta
import random

app = Flask(__name__)
app.secret_key = 'your-secret-key-here'

# 数据文件路径
DATA_DIR = 'data'
USERS_FILE = os.path.join(DATA_DIR, 'users.json')
TASKS_FILE = os.path.join(DATA_DIR, 'tasks.json')
REWARDS_FILE = os.path.join(DATA_DIR, 'rewards.json')

# 初始化数据
def init_data():
    if not os.path.exists(DATA_DIR):
        os.makedirs(DATA_DIR)
    
    # 初始化用户数据
    if not os.path.exists(USERS_FILE):
        users = {
            "parent": {
                "username": "parent",
                "password": "parent123",
                "role": "parent",
                "child_id": "child"
            },
            "child": {
                "username": "child",
                "password": "child123",
                "role": "child",
                "points": 0,
                "badges": []
            }
        }
        with open(USERS_FILE, 'w', encoding='utf-8') as f:
            json.dump(users, f, ensure_ascii=False, indent=2)
    
    # 初始化任务数据
    if not os.path.exists(TASKS_FILE):
        tasks = []
        # 生成过去30天的模拟数据
        for i in range(30):
            date = datetime.now() - timedelta(days=29-i)
            tasks.append({
                "date": date.strftime("%Y-%m-%d"),
                "child_id": "child",
                "tasks": [
                    {
                        "id": 1,
                        "name": "完成作业",
                        "completed": random.choice([True, False]),
                        "points": 10
                    },
                    {
                        "id": 2,
                        "name": "整理房间",
                        "completed": random.choice([True, False]),
                        "points": 5
                    },
                    {
                        "id": 3,
                        "name": "阅读30分钟",
                        "completed": random.choice([True, False]),
                        "points": 8
                    }
                ]
            })
        with open(TASKS_FILE, 'w', encoding='utf-8') as f:
            json.dump(tasks, f, ensure_ascii=False, indent=2)
    
    # 初始化奖励数据
    if not os.path.exists(REWARDS_FILE):
        rewards = {
            "badges": [
                {"id": 1, "name": "早起鸟", "description": "连续7天早起", "icon": "🌅", "required_points": 50},
                {"id": 2, "name": "学习达人", "description": "完成所有学习任务", "icon": "📚", "required_points": 100},
                {"id": 3, "name": "整理小能手", "description": "连续5天整理房间", "icon": "✨", "required_points": 75},
                {"id": 4, "name": "阅读之星", "description": "累计阅读10小时", "icon": "⭐", "required_points": 150}
            ],
            "rewards": [
                {"id": 1, "name": "30分钟游戏时间", "points_cost": 30},
                {"id": 2, "name": "选择晚餐菜单", "points_cost": 50},
                {"id": 3, "name": "周末外出游玩", "points_cost": 100},
                {"id": 4, "name": "购买新玩具", "points_cost": 200}
            ]
        }
        with open(REWARDS_FILE, 'w', encoding='utf-8') as f:
            json.dump(rewards, f, ensure_ascii=False, indent=2)

# 读取数据函数
def read_json(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        return json.load(f)

def write_json(filename, data):
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 登录页面
@app.route('/')
def login():
    return render_template('login.html')

# 登录验证
@app.route('/login', methods=['POST'])
def do_login():
    username = request.json.get('username')
    password = request.json.get('password')
    
    users = read_json(USERS_FILE)
    
    if username in users and users[username]['password'] == password:
        session['username'] = username
        session['role'] = users[username]['role']
        if users[username]['role'] == 'parent':
            session['child_id'] = users[username]['child_id']
        
        return jsonify({"success": True, "role": users[username]['role']})
    
    return jsonify({"success": False, "message": "用户名或密码错误"})

# 登出
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))

# 家长管理页面
@app.route('/parent')
def parent_dashboard():
    if 'username' not in session or session['role'] != 'parent':
        return redirect(url_for('login'))
    
    return render_template('parent_dashboard.html')

# 儿童页面
@app.route('/child')
def child_dashboard():
    if 'username' not in session or session['role'] != 'child':
        return redirect(url_for('login'))
    
    return render_template('child_dashboard.html')

# 获取家长数据
@app.route('/api/parent/data')
def get_parent_data():
    if 'username' not in session or session['role'] != 'parent':
        return jsonify({"error": "未授权"}), 401
    
    child_id = session['child_id']
    tasks = read_json(TASKS_FILE)
    rewards = read_json(REWARDS_FILE)
    users = read_json(USERS_FILE)
    
    # 获取孩子的数据
    child_data = users[child_id]
    
    # 计算统计数据
    child_tasks = [t for t in tasks if t['child_id'] == child_id]
    
    # 最近7天数据
    recent_tasks = child_tasks[-7:]
    completion_rates = []
    
    for day in recent_tasks:
        total_tasks = len(day['tasks'])
        completed_tasks = len([t for t in day['tasks'] if t['completed']])
        rate = (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
        completion_rates.append({
            "date": day['date'],
            "rate": round(rate, 1)
        })
    
    # 月度统计
    monthly_completed = sum(len([t for t in day['tasks'] if t['completed']]) 
                           for day in child_tasks[-30:])
    monthly_total = sum(len(day['tasks']) for day in child_tasks[-30:])
    monthly_rate = (monthly_completed / monthly_total * 100) if monthly_total > 0 else 0
    
    # 获取建议
    suggestions = generate_suggestions(child_tasks)
    
    return jsonify({
        "child_data": child_data,
        "completion_rates": completion_rates,
        "monthly_rate": round(monthly_rate, 1),
        "total_points": child_data['points'],
        "badges": child_data['badges'],
        "suggestions": suggestions
    })

# 获取儿童数据
@app.route('/api/child/data')
def get_child_data():
    if 'username' not in session or session['role'] != 'child':
        return jsonify({"error": "未授权"}), 401
    
    child_id = session['username']
    tasks = read_json(TASKS_FILE)
    rewards = read_json(REWARDS_FILE)
    users = read_json(USERS_FILE)
    
    # 获取今日任务
    today = datetime.now().strftime("%Y-%m-%d")
    today_tasks = None
    for task_day in tasks:
        if task_day['date'] == today:
            today_tasks = task_day['tasks']
            break
    
    if not today_tasks:
        # 创建今日任务
        today_tasks = [
            {"id": 1, "name": "完成作业", "completed": False, "points": 10},
            {"id": 2, "name": "整理房间", "completed": False, "points": 5},
            {"id": 3, "name": "阅读30分钟", "completed": False, "points": 8}
        ]
        tasks.append({
            "date": today,
            "child_id": child_id,
            "tasks": today_tasks
        })
        write_json(TASKS_FILE, tasks)
    
    # 获取用户数据
    user_data = users[child_id]
    
    # 计算下一个徽章进度
    next_badge = None
    for badge in rewards['badges']:
        if badge['name'] not in user_data['badges']:
            next_badge = badge
            break
    
    return jsonify({
        "today_tasks": today_tasks,
        "points": user_data['points'],
        "badges": user_data['badges'],
        "next_badge": next_badge,
        "available_rewards": rewards['rewards']
    })

# 更新任务状态
@app.route('/api/child/task/<int:task_id>', methods=['POST'])
def update_task(task_id):
    if 'username' not in session or session['role'] != 'child':
        return jsonify({"error": "未授权"}), 401
    
    child_id = session['username']
    data = request.json
    completed = data.get('completed', False)
    
    tasks = read_json(TASKS_FILE)
    users = read_json(USERS_FILE)
    
    # 找到今日任务
    today = datetime.now().strftime("%Y-%m-%d")
    for task_day in tasks:
        if task_day['date'] == today and task_day['child_id'] == child_id:
            for task in task_day['tasks']:
                if task['id'] == task_id:
                    task['completed'] = completed
                    
                    # 更新积分
                    if completed:
                        users[child_id]['points'] += task['points']
                    else:
                        users[child_id]['points'] = max(0, users[child_id]['points'] - task['points'])
                    
                    write_json(TASKS_FILE, tasks)
                    write_json(USERS_FILE, users)
                    
                    return jsonify({"success": True, "points": users[child_id]['points']})
    
    return jsonify({"error": "任务未找到"}), 404

# 兑换奖励
@app.route('/api/child/redeem', methods=['POST'])
def redeem_reward():
    if 'username' not in session or session['role'] != 'child':
        return jsonify({"error": "未授权"}), 401
    
    child_id = session['username']
    reward_id = request.json.get('reward_id')
    
    users = read_json(USERS_FILE)
    rewards = read_json(REWARDS_FILE)
    
    # 找到奖励
    reward = None
    for r in rewards['rewards']:
        if r['id'] == reward_id:
            reward = r
            break
    
    if not reward:
        return jsonify({"error": "奖励未找到"}), 404
    
    # 检查积分
    if users[child_id]['points'] < reward['points_cost']:
        return jsonify({"error": "积分不足"}), 400
    
    # 扣除积分
    users[child_id]['points'] -= reward['points_cost']
    write_json(USERS_FILE, users)
    
    return jsonify({"success": True, "points": users[child_id]['points']})

# 生成管理建议
def generate_suggestions(tasks):
    suggestions = []
    
    # 分析最近7天的数据
    recent_tasks = tasks[-7:]
    
    # 计算各类任务的完成率
    task_stats = {}
    for day in recent_tasks:
        for task in day['tasks']:
            name = task['name']
            if name not in task_stats:
                task_stats[name] = {'completed': 0, 'total': 0}
            task_stats[name]['total'] += 1
            if task['completed']:
                task_stats[name]['completed'] += 1
    
    # 生成建议
    for task_name, stats in task_stats.items():
        rate = stats['completed'] / stats['total'] * 100
        if rate < 50:
            suggestions.append({
                "type": "warning",
                "title": f"{task_name}完成率较低",
                "content": f"最近7天{task_name}的完成率只有{rate:.0f}%，建议制定更具体的计划。"
            })
    
    # 如果整体完成率高，给出鼓励
    overall_completed = sum(len([t for t in day['tasks'] if t['completed']]) 
                             for day in recent_tasks)
    overall_total = sum(len(day['tasks']) for day in recent_tasks)
    overall_rate = overall_completed / overall_total * 100 if overall_total > 0 else 0
    
    if overall_rate > 80:
        suggestions.append({
            "type": "success",
            "title": "表现优秀",
            "content": f"最近7天整体完成率达到{overall_rate:.0f}%，继续保持！"
        })
    
    if len(suggestions) == 0:
        suggestions.append({
            "type": "info",
            "title": "保持稳定",
            "content": "各项任务完成稳定，建议保持当前节奏。"
        })
    
    return suggestions

if __name__ == '__main__':
    init_data()
    app.run(debug=True, host='0.0.0.0', port=5000)
